package com.sky.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jettison.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    final static int TIMEOUT = 1000;
    final static int TIMEOUT_MSEC=5*1000;

    public static String doGet(String url, Map<String,String> paramMap) {
        String str="";
        CloseableHttpClient HttpClient = HttpClients.createDefault();
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if(paramMap != null){
                for (String key : paramMap.keySet()) {
                    uriBuilder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = uriBuilder.build();
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse res = HttpClient.execute(httpGet);
            if(res.getStatusLine().getStatusCode() == 200){
                str = EntityUtils.toString(res.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return str;
    }
    public static String doPost(String url, Map<String,String> paramMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            if (paramMap != null) {
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(),param.getValue());
                }
                StringEntity stringEntity = new StringEntity(jsonObject.toString());
                stringEntity.setContentEncoding("utf-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
                response = httpClient.execute(httpPost);
            }
            // 处理响应
            if(response.getStatusLine().getStatusCode() == 200){
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultString;
    }
}
